#!/usr/bin/env python
# coding=utf-8
import gzip
import tarfile
import zipfile
import os
import shutil
import base64


# 主函数,传入带路径的压缩文件名
def extract(file):
    fileType = os.path.splitext(file)[1]
    if fileType.upper() == '.ZIP':
        return un_zip(file)
    if fileType.upper() == '.GZ':
        return un_gz(file)
    if fileType.upper() == '.TAR':
        return un_tar(file)
    return [False, '文件类型暂时不受支持']


def un_gz(file):
    try:
        fileName = file.replace(".gz", "")
        g_file = gzip.GzipFile(file)
        with open(fileName, "wb+") as f:
            f.write(g_file.read())
        g_file.close()
    except Exception as e:
        return [False, e]
    else:
        return [True]


def un_tar(file):
    try:
        tar = tarfile.open(file)
        names = tar.getnames()
        os.mkdir(file + "_files")
        for name in names:
            tar.extract(name, file + "_files/")
        tar.close()
    except Exception as e:
        return [False, e]
    else:
        return [True]


def un_zip(file):
    try:
        zip_file = zipfile.ZipFile(file)
        os.mkdir(file + "_files")
        nameDict = {}
        for names in zip_file.namelist():
            oldname = names
            try:
                names = names.encode('cp437').decode('gbk')
            except:
                names = names.encode('utf-8').decode('utf-8')
            nameDict[oldname] = names
            zip_file.extract(oldname, file + "_files/")
        zip_file.close()
        # zipfile解压中文文件名会乱码,所以解压完后要重命名回正常的文件名
        for k, v in nameDict.items():
            os.rename(file + "_files/"+k, file + "_files/"+v)
    except Exception as e:
        return [False, e]
    else:
        return [True]


# 文件处理
def delete_(fileName):
    try:
        if os.path.exists(fileName):
            if os.path.isfile(fileName):
                os.remove(fileName)
            else:
                shutil.rmtree(fileName)
        else:
            return [False, "文件或目录不存在"]
    except Exception as e:
        return [False, e]
    else:
        return [True]


def zip_(fileList, zipPath):
    try:
        if len(fileList) > 1:
            zipName = os.path.split(zipPath)[1]
        else:
            zipName = os.path.split(fileList[0])[1]
        zipName = ('根目录' if zipName == '' else zipName)
        f = zipfile.ZipFile(os.path.join(zipPath, zipName) +
                            '[打包下载].zip', 'w', zipfile.ZIP_DEFLATED)
        for i in fileList:
            if os.path.isdir(i):
                for dirpath, dirnames, filenames in os.walk(i):
                    for filename in filenames:
                        f.write(os.path.join(dirpath, filename))
            else:
                f.write(i)
        f.close()
    except Exception as e:
        return [False, e]
    else:
        return [True, os.path.join(zipPath, zipName)+'[打包下载].zip']


def copy_(copyFile, path):
    try:
        if os.path.isdir(copyFile):
            # 将要复制过来的文件夹名
            newPath = os.path.join(path, os.path.split(copyFile)[1])
            if not os.path.exists(os.path.join(path, os.path.split(copyFile)[1])):
                os.mkdir(newPath)
            else:
                return [False, '要复制的文件夹已存在！']
            shutil.copytree(copyFile, path)
        else:
            if not os.path.exists(os.path.join(path, os.path.split(copyFile)[1])):
                shutil.copy(copyFile, path)
            else:
                return [False, '要复制的文件已存在！']
    except Exception as e:
        return [False, e]
    else:
        return [True]


def cut_(cutFile, path):
    try:
        if os.path.exists(os.path.join(path, os.path.split(cutFile)[1])):
            return [False, '要剪切的文件已存在！']
        shutil.move(cutFile, path)
    except Exception as e:
        return [False, e]
    else:
        return [True]


# 获取文件大小
def getFileSize(filePath):
    try:
        size = float(os.path.getsize(filePath))
        return formatSize(size)
    except Exception as err:
        return err


# 获取文件夹大小
def getFilesSize(filePath):
    sumsize = 0
    try:
        filename = os.walk(filePath)
        for root, dirs, files in filename:
            for fle in files:
                path = os.path.join(root, fle)
                if os.path.exists(path):
                    size = os.path.getsize(path)
                    sumsize += size
        return formatSize(sumsize)
    except Exception as err:
        return err


# 格式化文件大小
def formatSize(byte):
    filesizes = ''
    filesizeK = byte / 1024
    if filesizeK >= 1024:
        filesizeM = filesizeK/1024
        if filesizeM >= 1024:
            filesizeG = filesizeM/1024
            filesizes = str(round(filesizeG, 2)) + 'G'
        else:
            filesizes = str(round(filesizeM, 2)) + 'M'
    else:
        filesizes = str(round(filesizeK, 2)) + 'K'
    return filesizes


def b64decode_(v):
    try:
        return base64.b64decode(v).decode()
    except:
        return base64.b64decode(v.replace(' ', '+')).decode()
